import React, { Component } from 'react';

import { Typography, Descriptions, Space, Table, Avatar, Modal, Button, List, Image, Radio } from 'antd';
import VirtualList from 'rc-virtual-list';
import TheImage from '@/components/TheImage'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import { UserOutlined } from '@ant-design/icons'
import TheButton from '@/components/TheButton'
import GoBack from '@/components/TheGoBack';
import enums from '../Enum'
import HandleDialog from '../components/handleDialog'
import store from "@/store/store"

import { transNumber } from "@/utils/numberTrans";
import {
    apiGetMemberReviewRecordsDetail,
    apiFindUnblockingRecordsByMemberId,
    apiMemberAppealRecordsDetail
} from '@/request/riskControl'
import { apiGetOneMessageHistoryReport, apiGetOneMessageHistory } from "@/request/app/sensitiveWords";

import './style.less'
const { Paragraph, Link, Text } = Typography;

class View extends Component {
    constructor(props) {
        super(props);
        this.handleRefs = React.createRef()
        this.state = {
            listLoading: false,
            imMsgVisible: false,
            imMsgData: [],

            columns: [
                {
                    title: "ID",
                    dataIndex: "recordId",
                    key: "recordId",
                },
                {
                    title: "类型",
                    dataIndex: "bannedTypeText",
                    key: "bannedTypeText",
                },
                {
                    title: "处理意见",
                    dataIndex: "handlingOpinions",
                    key: "handlingOpinions",
                    render: (text, record) => {
                        return <Text
                            style={{ width: 300 }}
                            ellipsis={{
                                tooltip: text,
                            }}
                        >
                            {text}
                        </Text>
                    }
                },
                {
                    title: "封禁时间",
                    dataIndex: "bannedTime",
                    key: "bannedTime",
                },
                {
                    title: "解封时间",
                    dataIndex: "unsealTime",
                    key: "unsealTime",
                },
                {
                    title: "操作",
                    fixed: "right",
                    width: 200,
                    render: (text, render) => {
                        return (
                            render.reportingRecordsId !== 'null' && <div>
                                <TheButton onClick={() => this.goView(render.reportingRecordsId)}>查看</TheButton>
                            </div>
                        );
                    },
                },
            ],
            tableData: [],
            dataSource: {},
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            total: 0,
            type: '',//reportDoing 举报处理 report 举报查看 appeal 申诉查看 appealDoing 申诉处理
            memberId: null,
            snapshot: {
                sights: [],
                content: [],
                banned: [],
                state: '',
                disposeImages: [],
                disposeOpinion: ''
            },//快照
            hrefMode: '',
            sendTimeById: '',
            scrollDom: null,
            downNotMore: false,
            upNotMore: false,

        }
    }
    componentWillUnmount() {
        store.dispatch({
            type: 'startManualLoad',
        })
    }
    componentDidMount() {
        console.log();
        const urlParams = new URLSearchParams(this.props.location.search);
        const hrefMode = urlParams.get('mode');
        this.setState({
            hrefMode
        })
        this.getData()

    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        if (prevProps.match.params.id !== this.props.match.params.id) {
            this.getData()
        }
    }

    getData = () => {
        const { reportState, reportState_content, appealState, appealState_content, BANNED_state } = enums
        let { type, id } = this.props.match.params;
        if (type === 'report' || type === 'reportDoing') {
            apiGetMemberReviewRecordsDetail(id).then(res => {
                if (res.code === 0) {
                    const sights = [], content = [], banned = []
                    res.data.snapshootList.forEach(item => {
                        if (item.bannedType in reportState) {
                            sights.push(item)
                        } else if (item.bannedType in reportState_content) {
                            content.push(item)
                        } else if (item.bannedType in BANNED_state) {
                            sights.push(item)
                        }
                    })
                    this.setState({
                        type,
                        dataSource: res.data,
                        tableData: res.data.list,
                        snapshot: {
                            sights: sights || [],
                            banned,
                            content,
                            state: res.data.state || '',
                            disposeImages: res.data.disposeImages ? res.data.disposeImages.split(',') : [],
                            disposeOpinion: res.data.disposeOpinion || ''
                        }
                    })
                }
            })
        } else {
            apiMemberAppealRecordsDetail({
                appealId: id
            }).then(res => {
                if (res.code === 0) {
                    const sights = [], content = []
                    res.data.snapshootList.forEach(item => {
                        if (item.bannedType in appealState) {
                            sights.push(item)
                        } else if (item.bannedType in appealState_content) {
                            content.push(item)
                        }
                    })
                    this.setState({
                        type,
                        dataSource: res.data,
                        tableData: res.data.historyBannedRecords,
                        snapshot: {
                            sights: sights || [],
                            content,
                            state: '',
                            disposeImages: res.data.handlingOpinionsImage ? res.data.handlingOpinionsImage.split(',') : [],
                            disposeOpinion: res.data.handlingOpinions || ''
                        }
                    })
                }
            })
        }
    }
    goView = (id) => {
        const w = window.open('about:blank');
        w.location.href = `/gl/#/riskControl/report/view/${id}?mode=blank`
    }
    //数据处理
    // getData = (values) => {
    //     let { pageData,memberId } = this.state
    //     apiFindUnblockingRecordsByMemberId({
    //         ...pageData,
    //         memberId
    //     }).then(res => {
    //         if (res.code === 0){
    //             this.setState({
    //                 tableData: res.data
    //             })
    //         }
    //     })
    // }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => {
            this.getData()
        })
    };
    getType = (val, type) => {
        const { reportState_content } = enums
        if (type == 'report' || type == 'reportDoing') {
            return ["MEMBER_CIRCLE_COMMENT", "MEMBER_CIRCLE_DYNAMIC"].includes(val)
        } else {
            return Object.keys(reportState_content).includes(val)
        }
    }
    onCloseImMsg = () => {
        this.state.scrollDom.removeEventListener('scroll', () => { })
        store.dispatch({
            type: 'startManualLoad',
        })
        this.setState({
            imMsgVisible: false,
            imMsgData: []
        })
    }
    viewImgMsg = ({
        sendId = '', receiveId = '',
        time = '', type = 'down'
    } = {}) => {
        const { imMsgType } = enums
        let params = {}
        if (type == 'init') {
            params = {
                pageSize: 10,
                sendId,
                receiveId,
                sendTime: new Date(time).getTime(),
            }
        } else {
            console.log(1111);
            params = {
                pageSize: 10,
                sendId,
                receiveId,
                pointSeq: type == 'up' ? this.state.imMsgData[0].seq : this.state.imMsgData[this.state.imMsgData.length - 1].seq,
                action: type == 'up' ? 0 : 1,//0 向上翻页 1向下翻页
            }
        }
        if (type == "up" && params.pointSeq <= 1) {
            this.setState({
                upNotMore: true
            })
            return false
        }
        store.dispatch({
            type: 'stopManualLoad',
        })
        apiGetOneMessageHistoryReport(params).then(res => {
            if (res.code === 0) {

                let sendTimeById = this.state.sendTimeById
                const imData = res.data.data.map(item => {
                    let { messageBody, isEncrypt } = item.content
                    try {
                        messageBody = JSON.parse(messageBody)
                        messageBody.imgMsgType = imMsgType[`imMsgType_${messageBody.messageType}`]
                    } catch (error) {
                        messageBody = JSON.parse(messageBody)
                        messageBody.imgMsgType = imMsgType[`imMsgType_${messageBody.messageType}`]
                    }
                    if (item.sendTime <= time && type == 'init') {
                        sendTimeById = item.sendTime
                    }
                    return {
                        ...item,
                        content: {
                            isEncrypt,
                            messageBody
                        }
                    }
                })
                if (type == 'down' && imData.length == 0) {
                    React.$message({
                        type: 'warning',
                        content: "本次查询没有更多了"
                    })
                }
                this.setState({
                    imMsgVisible: true,
                    imMsgData: type == 'up' ? imData.concat(...this.state.imMsgData) : this.state.imMsgData.concat(...imData),
                    sendTimeById,
                    upNotMore: type == 'up' && imData.length < 10,
                    downNotMore: type == 'down' && imData.length < 10
                }, () => {
                    if (!this.state.scrollDom) {
                        const dom = document.querySelectorAll('.mesBox')[0]
                        dom.addEventListener('scroll', (e) => {
                            if (dom.scrollTop + dom.clientHeight >= dom.scrollHeight) {
                                this.viewImgMsg({ sendId: this.state.dataSource.reportMemberId, receiveId: this.state.dataSource.dataId, pointSeq: this.state.imMsgData[this.state.imMsgData.length - 1].seq, type: "down" })

                            } else if (dom.scrollTop <= 0) {
                                this.viewImgMsg({ sendId: this.state.dataSource.reportMemberId, receiveId: this.state.dataSource.dataId, pointSeq: this.state.imMsgData[0].seq, type: "up" })
                            }
                        })
                        this.setState({
                            scrollDom: dom
                        })
                    }

                })


            }
        })

    }
    getDescription = (row) => {
        const { reviewDescribe } = this.state.dataSource
        const keyIndex = reviewDescribe.indexOf('涉嫌自定义违禁词：')

        if (row.content.messageBody) {
            let { imgMsgType, content } = row.content.messageBody
            try {
                content = JSON.parse(content)
            } catch (error) {
            }
            if (imgMsgType == 'text') {
                return <div>{row.content.messageBody?.content}</div>
                console.log(keyIndex);
                if (keyIndex > -1) {
                    let keyStr = reviewDescribe.split('涉嫌自定义违禁词：')[1]
                    let doms = row.content.messageBody?.content.split(keyStr)
                    const str = doms.map((item, index) => {
                        if (index < doms.length - 1) {
                            return <span>{item}<span className='redTxt'>{keyStr}</span></span>
                        } else {
                            return <span>{item}</span>
                        }
                    })
                    return <div>{str}</div>
                } else {
                    return <div>{row.content.messageBody?.content}</div>
                }
            } else if (imgMsgType == 'transfer') {
                return <div>【转账 ￥{transNumber((Number.parseFloat(content.money) / 100), 2)}】{content.title}</div>
            } else if (imgMsgType == 'redPacket') {
                return <div>【红包】{content.title}</div>
            } else if (imgMsgType == 'gift') {
                return <>
                    <img style={{ width: 50 }} src={content.image} alt="礼物" />
                    <span>{content.title}【礼物】</span>
                </>
            } else if (imgMsgType == 'video') {
                return <>
                    <video style={{ width: 200, height: 100, background: '#000' }} controls src={content.url} alt="视频"></video>
                </>
            } else if (imgMsgType == 'audio') {
                return <>
                    <audio controls src={content.url} alt="音频"></audio>
                </>
            } else if (imgMsgType == 'image') {
                return <>
                    <Image
                        width={100}
                        src={content.url}
                    />
                </>
            }
        } else {
            return '空'
        }
    }
    GoBack() {
        const { type } = this.state
        this.props.history.replace(`/riskControl/${['report', 'reportDoing'].includes(type) ? 'report' : 'appeal'}`)
    }
    onScroll = (e) => {

    }
    render() {
        const { upNotMore, downNotMore, type, columns, listLoading, dataSource, pageData, total, tableData, imMsgVisible, imMsgData, snapshot, hrefMode, sendTimeById } = this.state;
        let { commonHeaderType, commonHeaderReportType, reportState } = enums;
        return (
            <div className='p-layout-box commodity-content'>
                <GoBack history={hrefMode ? () => this.GoBack() : this.props.history} title={'详情'} />
                {
                    ['reportDoing'].includes(type) && dataSource.reviewStatus == 'N' && <TheButton style={{
                        position: 'absolute',
                        top: 30,
                        right: 50,
                    }} type="primary" size="middle" haspermi={['riskControl:report:dispose']} onClick={() => this.handleRefs.open({ id: dataSource.memberReviewRecordsId, mode: 'F', type: this.getType(dataSource.reviewType, 'reportDoing') ? "content" : 'user', from: "report" })}>去处理</TheButton>
                }
                {
                    ['appealDoing'].includes(type) && dataSource.state == 0 && <TheButton style={{
                        position: 'absolute',
                        top: 30,
                        right: 50,
                    }} type="primary" size="middle" haspermi={['riskControl:appeal:dispose']} onClick={() => this.handleRefs.open({ id: dataSource.appealId, mode: 'J', type: this.getType(dataSource.appealType, 'appealDoing') ? "content" : 'user', from: "appeal" })}>去处理</TheButton>
                }
                <Paragraph>
                    <blockquote>{commonHeaderType[type]}内容</blockquote>
                </Paragraph>
                <Descriptions title="" column={3}>
                    {
                        ['report', 'reportDoing'].includes(type) ? <>
                            <Descriptions.Item label="举报对象ID">
                                <Link
                                    href={`#/users/details/${dataSource.reportMemberId}`}>{dataSource.reportMemberId}</Link>
                            </Descriptions.Item>
                            <Descriptions.Item label={`举报人ID`}>
                                <Link href={`#/users/details/${dataSource.memberId}`} disabled={!dataSource.memberId}>{dataSource.memberId || '系统'}</Link>
                            </Descriptions.Item>
                            <Descriptions.Item label={`举报时间`}>
                                {dataSource.createTime}
                            </Descriptions.Item>
                            <Descriptions.Item label="举报对象昵称">
                                <Link href={`#/users/details/${dataSource.reportMemberId}`}>{dataSource.reportMemberName}</Link>
                            </Descriptions.Item>
                            <Descriptions.Item label={`举报人昵称`}>
                                <Link href={`#/users/details/${dataSource.memberId}`} disabled={!dataSource.memberId}>{dataSource.memberName || '系统'}</Link>
                            </Descriptions.Item>

                            <Descriptions.Item label={`处理时间`}>
                                {snapshot.sights && snapshot.sights.length > 0 ? snapshot.sights[0].bannedTime : '-'}
                            </Descriptions.Item>
                            <Descriptions.Item label={`举报类型`} span={3}>{commonHeaderReportType[dataSource.reviewType]}</Descriptions.Item>
                            <Descriptions.Item label="举报原因" span={3}>{dataSource.reviewReason}</Descriptions.Item>
                            <Descriptions.Item label={`举报描述`} span={3}>
                                <p>
                                    {
                                        dataSource.reviewType === "MEMBER_CHAT_PERMISSION" &&
                                        <div style={{ color: '#2ba3ff', cursor: 'pointer' }} onClick={() => this.viewImgMsg({ sendId: dataSource.reportMemberId, receiveId: dataSource.dataId, time: dataSource.messageTime, type: 'init' })}>查看上下文</div>
                                    }
                                    {dataSource.reviewDescribe}
                                </p>
                            </Descriptions.Item>
                            <Descriptions.Item label="相关凭证" span={3}>
                                <Space>
                                    {
                                        dataSource.reviewImages && dataSource.reviewImages.split(',').map((item, index) => {
                                            return <TheImage src={item} width={80} height={80} />
                                        })
                                    }
                                </Space>
                            </Descriptions.Item>
                            {
                                dataSource.petDynamicId && <Descriptions.Item label="动态编号" span={3}>
                                    <Link href={`#/petCircleUtil/dynamic/view/${dataSource.petDynamicId}`}>{dataSource.petDynamicId}</Link>
                                </Descriptions.Item>
                            }
                            {
                                dataSource.commentsText && <Descriptions.Item label="评论" span={3}>
                                    {dataSource.commentsText}
                                </Descriptions.Item>
                            }
                        </> : <>
                            <Descriptions.Item label={`申诉人ID`}>
                                <Link href={`#/users/details/${dataSource.applicantId}`}>{dataSource.applicantId}</Link>
                            </Descriptions.Item>
                            <Descriptions.Item label={`申诉人昵称`}>
                                <Link href={`#/users/details/${dataSource.applicantId}`}>{dataSource.applicantName}</Link>
                            </Descriptions.Item>
                            <Descriptions.Item label={`申诉类型`} span={2}>{reportState[dataSource.appealType]}</Descriptions.Item>
                            {
                                dataSource.reportingBehavior && <Descriptions.Item label="举报行为" span={2}>{dataSource.reportingBehavior}</Descriptions.Item>
                            }
                            <Descriptions.Item label={`申诉时间`} span={1}>{dataSource.createTime}</Descriptions.Item>
                            <Descriptions.Item label={`处理时间`} span={3}>{snapshot.sights && snapshot.sights.length > 0 ? snapshot.sights[0].unsealTime : '-'}</Descriptions.Item>

                            <Descriptions.Item label={`申诉描述`} span={3}>

                                <p>

                                    {dataSource.appealDescription}
                                </p>
                            </Descriptions.Item>
                            <Descriptions.Item label="相关凭证" span={3}>
                                <Space>
                                    {
                                        dataSource.relatedVouchers && dataSource.relatedVouchers.split(',').map((item, index) => {
                                            return <TheImage src={item} width={80} height={80} />
                                        })
                                    }
                                </Space>
                            </Descriptions.Item>
                            {
                                dataSource.dynamicId && <Descriptions.Item label="动态编号" span={2}>
                                    <Link href={`#/petCircleUtil/dynamic/view/${dataSource.dynamicId}`}>{dataSource.dynamicId}</Link>
                                </Descriptions.Item>
                            }
                            {
                                dataSource.comment && <Descriptions.Item label="评论" span={2}>
                                    {dataSource.comment}
                                </Descriptions.Item>
                            }
                        </>
                    }
                </Descriptions>
                <Paragraph>
                    <blockquote>历史违规记录</blockquote>
                </Paragraph>
                <Table
                    columns={columns}
                    pagination={{
                        position: ['bottomCenter'],
                    }}
                    dataSource={tableData}
                    rowKey={(record) => record.recordId}
                />
                {
                    ['reportDoing', 'report'].includes(type) && dataSource.reviewStatus !== 'N' && <>
                        <Paragraph>
                            <blockquote>处理操作</blockquote>
                        </Paragraph>
                        <Descriptions title="处理举报对象" column={1} style={{ padding: ' 0 20px' }}>
                            <Descriptions.Item label="处理类型">
                                <div>
                                    <p>
                                        {enums.handleState.report[snapshot.sights && snapshot.sights.length > 0 ? snapshot.sights[0].state : '']}

                                    </p>
                                    <div className='sights'>
                                        {
                                            snapshot.sights.map(item => {
                                                const state = snapshot.sights && snapshot.sights.length > 0 ? snapshot.sights[0].state : ''
                                                return state === 'BLOCKED' || state === 'BANNED' ? <>
                                                    {enums.reportState[item.bannedType]}
                                                    {enums.BANNED_state[item.bannedType]}
                                                    <div style={{ padding: ' 0 20px' }}>
                                                        <Radio.Group value={item.bannedTimeType} disabled>
                                                            <Radio value={"1"}>临时封禁  解封时间 {item.bannedEndTime}</Radio>

                                                            <br></br>
                                                            <Radio value={"0"}>永久封禁</Radio>
                                                        </Radio.Group>
                                                    </div>
                                                </> : null
                                            })
                                        }
                                    </div>
                                </div>
                            </Descriptions.Item>
                            {
                                snapshot.content && snapshot.content.length > 0 && <Descriptions.Item >
                                    <Descriptions title="处理举报内容" column={1} style={{ padding: ' 0 ' }}>
                                        <Descriptions.Item label="处理类型">
                                            {
                                                enums.handleState.contentState[snapshot.content && snapshot.content.length > 0 ? snapshot.content[0].state : '']
                                            }
                                        </Descriptions.Item>

                                    </Descriptions>
                                </Descriptions.Item>
                            }


                            <Descriptions.Item label="处理意见">
                                {
                                    snapshot.disposeOpinion
                                }
                            </Descriptions.Item>
                            <Descriptions.Item label="处理意见">
                                {
                                    <Space>
                                        {
                                            snapshot.disposeImages.map((item, index) => {
                                                return <TheImage src={item} width={80} height={80} />
                                            })
                                        }
                                    </Space>
                                }
                            </Descriptions.Item>
                        </Descriptions>
                    </>
                }
                {
                    ['appealDoing', 'appeal'].includes(type) && dataSource.state != 0 && <>
                        <Paragraph>
                            <blockquote>处理操作</blockquote>
                        </Paragraph>
                        <Descriptions title="处理举报对象" column={1} style={{ padding: ' 0 20px' }}>
                            <Descriptions.Item label="处理类型">
                                <div>
                                    <p>
                                        解禁
                                    </p>
                                    <div className='sights'>
                                        {
                                            snapshot.sights.map(item => {
                                                return <p>{item.bannedTypeText}</p>
                                            })
                                        }
                                    </div>
                                </div>
                            </Descriptions.Item>
                            {
                                snapshot.content && snapshot.content.length > 0 && <Descriptions.Item >
                                    <Descriptions title="处理举报内容" column={1} style={{ padding: ' 0 ' }}>
                                        <Descriptions.Item label="处理类型">
                                            {
                                                enums.handleState.appealState[snapshot.content && snapshot.content.length > 0 ? snapshot.content[0].state : '']
                                            }
                                        </Descriptions.Item>

                                    </Descriptions>
                                </Descriptions.Item>
                            }

                            <Descriptions.Item label="处理意见">
                                {
                                    snapshot.disposeOpinion
                                }
                            </Descriptions.Item>
                            <Descriptions.Item label="处理意见">
                                {
                                    <Space>
                                        {
                                            snapshot.disposeImages.map((item, index) => {
                                                return <TheImage src={item} width={80} height={80} />
                                            })
                                        }
                                    </Space>
                                }
                            </Descriptions.Item>
                        </Descriptions>
                    </>
                }



                {/*<TheTable*/}
                {/*    columns={columns}*/}
                {/*    dataSource={tableData}*/}
                {/*    rowKey={(record) => record.reportingRecordsId}*/}
                {/*/>*/}
                {/*<ThePagination*/}
                {/*    pageNo={pageData.pageNo}*/}
                {/*    pageSize={pageData.pageSize}*/}
                {/*    total={total}*/}
                {/*    pageChange={this.pageChange}*/}
                {/*/>*/}
                <HandleDialog ref={ref => this.handleRefs = ref} getData={this.getData}></HandleDialog>
                <Modal
                    visible={imMsgVisible}
                    title={'上下文'}
                    width={800}
                    onCancel={this.onCloseImMsg}
                    footer={[
                        <Button onClick={this.onCloseImMsg}>
                            关 闭
                        </Button>
                    ]}
                >
                    <div className='mesBox'>
                        <div className='more'>{upNotMore && '没有更多了'}</div>
                        <List
                            loading={listLoading}
                            itemLayout="horizontal"
                            dataSource={imMsgData}
                            renderItem={(item, index) => (
                                <List.Item
                                >
                                    {
                                        item.fromUid != dataSource.reportMemberId ?
                                            <div className='left' >
                                                <Avatar className='avatar' size="large" src={item.content.messageBody?.from_avatar} icon={<UserOutlined />} />
                                                <div className='content'>
                                                    <div className="name">{item.content.messageBody?.from_name}</div>
                                                    <div className="desc" style={{ background: item.sendTime === sendTimeById ? '' : '', color: item.sendTime === sendTimeById ? '' : '' }}>{this.getDescription(item)}</div>
                                                </div>
                                            </div> :
                                            <div className='right' >
                                                <div className='content'>
                                                    <div className="name">{item.content.messageBody?.from_name}</div>
                                                    <div className="desc" style={{ background: item.sendTime === sendTimeById ? '' : '', color: item.sendTime === sendTimeById ? '' : '' }}>{this.getDescription(item)}</div>
                                                </div>
                                                <Avatar size="large" className='avatar' src={item.content.messageBody?.from_avatar} icon={<UserOutlined />} />
                                            </div>
                                    }


                                </List.Item>
                            )}

                        >
                            {
                                imMsgData.length <= 6 &&
                                <div className='more' onClick={() => this.viewImgMsg({ sendId: dataSource.reportMemberId, receiveId: dataSource.dataId, type: 'down' })}>本次查询没有更多了</div>
                            }
                        </List>
                    </div>



                </Modal>
            </div>
        );
    }
}

export default View;
